const _ = require("lodash");

/* 生成dom随机id */
export function getRandomId (length = 10) {
  return Number(Math.random().toString().substr(3, length) + Date.now()).toString(36);
}

/* 生成随机字符串 */
export function getRandomString (length = 10) {
  let result = "";
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  const charactersLength = characters.length;
  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength));
  }
  return result;
}

/**
 * Created by Syaoran on 2021/12/29.
 * 重置对象所有的属性值
 * @param { Object } obj: 要处理的对象
 * @param { Array } list: 要忽略的键名
 */
export function resetObject (obj, list) {
  if (!_.isObject(obj)) return;
  for (let key in obj) {
    const ignoreIndex = _.findIndex(list, item => {
      return item === key;
    });
    if (ignoreIndex === -1) {
      if (_.isArray(obj[key])) obj[key] = [];
      else if (_.isObject(obj[key])) obj[key] = resetObject(obj[key]);
      else obj[key] = "";
    }
  }
  return obj;
}

/**
 * 将数组按某个属性名递归为一维数组
 */
export function flattenDeepBy (array = [], key = "children") {
  const result = [];
  const flatten = (arr) => {
    arr.forEach(i => {
      result.push(i);
      if (i[key] && _.isArray(i[key]) && i[key].length) flatten(i[key]);
    });
  };
  flatten(array);
  return result;
}

/**
 * Created by Syaoran on 2021/12/23.
 * 将对象中的下划线命名替换为驼峰式命名
 * @param {String} obj: 要转换的对象
 */
export function jsonToHump(obj) {
  if (_.isArray(obj)) {
    obj.forEach(i => {
      jsonToHump(i);
    });
  } else if (_.isObject(obj)) {
    _.forIn(obj, (value, key) => {
      const newKey = _.camelCase(key);
      if (key !== newKey) {
        obj[newKey] = value;
        delete obj[key];
      }
      jsonToHump(obj[newKey]);
    });
  }
}

/**
 * Created by Syaoran on 2022/7/27.
 * 将对象、数组中的undefined转为空string
 * @param {String} obj: 要转换的对象
 */
export function formatObjectUndefined (obj) {
  const object = _.forIn(obj, (value, key) => {
    console.log(key + ":", value);
    if (_.isArray(value)) value = formatArrayUndefined(value);
    else if (_.isObject(value)) value = formatObjectUndefined(value);
    else if (value === undefined) value = "";
    console.log("value:", value);
  });
  return object;
}
export function formatArrayUndefined (arr) {
  const array = _.cloneDeep(arr);
  array.forEach(item => {
    if (_.isArray(item)) item = formatArrayUndefined(item);
    else if (_.isObject(item)) item = formatObjectUndefined(item);
    else if (item === undefined) item = "";
  });
  return array;
}

/**
 * Created by Syaoran on 2021/11/22.
 * 星期的中英文互换
 * @param {String} week: 要转换的信息
 * @param {String} to: 目标格式 -> "en" | "ch" | "sta"
 */
export function formatWeek(week, to = "en") {
  if (to !== "en" && to !== "ch" && to !== "sta") {
    return;
  }
  const dict = [
    { en: "Monday", ch: "周一", sta: "星期一" },
    { en: "Tuesday", ch: "周二", sta: "星期二" },
    { en: "Wednesday", ch: "周三", sta: "星期三" },
    { en: "Thursday", ch: "周四", sta: "星期四" },
    { en: "Friday", ch: "周五", sta: "星期五" },
    { en: "Saturday", ch: "周六", sta: "星期六" },
    { en: "Sunday", ch: "周日", sta: "星期天" }
  ];
  const row = dict.find(row => {
    let match = "";
    for (let key in row) {
      if (row[key] === week) match = row;
    }
    return !!match;
  });
  return row[to];
}

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null;
  }
  const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}";
  let date;
  if (typeof time === "object") {
    date = time;
  } else {
    if (typeof time === "string" && /^[0-9]+$/.test(time)) {
      time = parseInt(time);
    }
    if (typeof time === "number" && time.toString().length === 10) {
      time = time * 1000;
    }
    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  };
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key];
    // Note: getDay() returns 0 on Sunday
    if (key === "a") {
      return ["日", "一", "二", "三", "四", "五", "六"][value];
    }
    return value.toString().padStart(2, "0");
  });
  return time_str;
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (("" + time).length === 10) {
    time = parseInt(time) * 1000;
  } else {
    time = +time;
  }
  const d = new Date(time);
  const now = Date.now();

  const diff = (now - d) / 1000;

  if (diff < 30) {
    return "刚刚";
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + "分钟前";
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + "小时前";
  } else if (diff < 3600 * 24 * 2) {
    return "1天前";
  }
  if (option) {
    return parseTime(time, option);
  } else {
    return (
      d.getMonth() +
      1 +
      "月" +
      d.getDate() +
      "日" +
      d.getHours() +
      "时" +
      d.getMinutes() +
      "分"
    );
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = url.split("?")[1];
  if (!search) {
    return {};
  }
  return JSON.parse(
    "{\"" +
      decodeURIComponent(search)
        .replace(/"/g, "\\\"")
        .replace(/&/g, "\",\"")
        .replace(/=/g, "\":\"")
        .replace(/\+/g, " ") +
      "\"}"
  );
}

// 时间转换为yyyy-MM-dd的字符串形式
// timeString((new Date()))
export function timeString(time) {
  // let time = new Date();
  let year = time.getFullYear();
  let month = time.getMonth() + 1;
  let day = time.getDate();
  if (month < 10) month = "0" + month;
  if (day < 10) day = "0" + day;
  return year + "-" + month + "-" + day;
}

// 对HH:mm:ss时间格式进行计算
export function calTimewithMinutes(time, min, type) {
  const HH = parseInt(time.split(":")[0]);
  const mm = parseInt(time.split(":")[1]);
  const ss = "00";
  min = parseInt(min, 10);
  let hour = 0;
  if (min > 60) {
    hour = parseInt(min / 60);
    min = Math.round(min % 60);
  }
  if (min < 0) {
    return undefined;
  }
  if (type === "reduce") {
    let resHH = HH - hour;
    let resmm = mm - min;
    if (resHH < 10) resHH = "0" + resHH;
    if (resmm < 10) resmm = "0" + resmm;
    return resHH + ":" + resmm + ":" + ss;
  } else {
    let resHH = HH + hour;
    if (resHH >= 24) {
      resHH = 0;
    }
    let resmm = mm + min;
    if (resmm >= 60) {
      resmm = resmm - 60;
      resHH = resHH + 1;
    }
    if (resHH >= 24) {
      resHH = 0;
    }
    if (resHH < 10) resHH = "0" + resHH;
    if (resmm < 10) resmm = "0" + resmm;
    return resHH + ":" + resmm + ":" + ss;
  }
}

//计算当前日期相隔X天后的日期
export function calculateDate(beginDate, count, type) {
  var date = new Date(beginDate);
  date.setDate(date.getDate() + count);
  var year = date.getFullYear();
  var month = ("0" + (date.getMonth() + 1)).slice(-2);
  var day = ("0" + date.getDate()).slice(-2);
  var hours = ("0" + date.getHours()).slice(-2);
  var minute = ("0" + date.getMinutes()).slice(-2);
  var second = ("0" + date.getSeconds()).slice(-2);
  let endDate = year + "-" + month + "-" + day;
  if (type === "date") {
    endDate = year + "-" + month + "-" + day;
  } else {
    endDate =
      year +
      "-" +
      month +
      "-" +
      day +
      " " +
      hours +
      ":" +
      minute +
      ":" +
      second;
  }
  return endDate;
}

// 计算时间间隔
export function calTimeDiff(time1, time2) {
  const timeDiff = new Date(time1).getTime() - new Date(time2).getTime();
  //计算出相差天数
  const days = Math.floor(timeDiff / (24 * 3600 * 1000));
  //计算出小时数
  const leave1 = timeDiff % (24 * 3600 * 1000);
  //计算天数后剩余的毫秒数
  const hours = Math.floor(leave1 / (3600 * 1000));
  //计算相差分钟数
  const leave2 = leave1 % (3600 * 1000);
  //计算小时数后剩余的毫秒数
  const minutes = Math.floor(leave2 / (60 * 1000));
  //计算相差秒数
  const leave3 = leave2 % (60 * 1000);
  //计算分钟数后剩余的毫秒数
  const seconds = Math.round(leave3 / 1000);
  const time = {
    days: days,
    hours: hours,
    minutes: minutes,
    seconds: seconds
  };
  return time;
}

/**
 * @param {string} input
 */

export function assertString(input) {
  const isString = typeof input === "string" || input instanceof String;

  if (!isString) {
    let type = typeof input;
    if (input === "null") type = "null";
    if (type === "object") type = input.constructor.name;

    throw Error(`Excepted a string but received a ${type}`);
  }
}
// 初始化表格拖拽事件，需要传入this.$refs.table与表格绑定的this.tabledata变量
import Sortable from "sortablejs";
export function setTableSort(table, tableData) {
  const el = table.$el.querySelectorAll(
    ".el-table__body-wrapper > table > tbody"
  )[0];
  const tableTable = Sortable.create(el, {
    ghostClass: "table-ghost",
    setData: function(dataTransfer) {
      dataTransfer.setData("Text", "");
    },
    onEnd: evt => {
      const targetRow = tableData.splice(evt.oldIndex, 1)[0];
      tableData.splice(evt.newIndex, 0, targetRow);
      let showingList = [];
      tableData.forEach(i => {
        showingList.push(i.admission_number);
      });
      console.log(showingList);
      // setTimeout(() => {
      //     _this.tableData.forEach(i=>{
      //         console.log(i.admission_number);
      //     });
      // }, 0);
    }
  });

  return tableTable;
}

/* base64 to file  */
export function dataURLtoFile(dataurl, filename) {
  const arr = dataurl.split(",");
  const mime = arr[0].match(/:(.*?);/)[1];
  const bstr = atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], filename, {
    type: mime
  });
}
/* 上移操作 */
export function moveUp(index, arr) {
  if (index === 0) return arr;
  arr[index] = arr.splice(index - 1, 1, arr[index])[0];
  return arr;
}
/* 下移操作 */
export function moveDown(index, arr) {
  if (index === arr.length - 1) return arr;
  arr[index] = arr.splice(index + 1, 1, arr[index])[0];
  return arr;
}
